package com.kfm.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@WebServlet("/cookie")
public class CookieServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        // 创建 Cookie 对象
        Cookie cookie = new Cookie("name", URLEncoder.encode("开发喵", StandardCharsets.UTF_8));
        Cookie msg = new Cookie("message", URLEncoder.encode("你好，开发喵", StandardCharsets.UTF_8));
        // 设置 Cookie 的存活时间 就将Cookie存储到浏览器所在的硬盘里 到期自动删除
        cookie.setMaxAge(60 * 60 * 24 * 7);
        // 发送 Cookie
        resp.addCookie(cookie);
        resp.addCookie(msg);
    }
}
